package com.ngkj.zmfptback.sys.evaluator;

import com.ngkj.zmfptback.sys.bean.RoleEntity;
import com.ngkj.zmfptback.sys.bean.UserEntity;
import com.ngkj.zmfptback.sys.service.read.UserReadService;
import com.ngkj.zmfptback.sys.service.write.UserWriteService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义登录验证
 * @author ChenHN
 * @since 2021/12/1 creation
 **/
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private UserReadService userReadService;

    @Resource
    private UserWriteService userWriteService;

    @Resource
    private BCryptPasswordEncoder encoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取表单中的用户名
        String username = (String) authentication.getPrincipal();
        //获取表单中的密码
        String password = (String) authentication.getCredentials();

        UserEntity userEntityInfo = (UserEntity) userDetailsService.loadUserByUsername(username);
        if (ObjectUtils.isEmpty(userEntityInfo)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
//        $2a$10$CUD0v9qU7Q2ncCUIFqnU2umtX0dIkOPaWwYMTOnWK1z7qQCGwHT4u

        //判断密码是否正确
        if (!encoder.matches(password,userEntityInfo.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }

        userEntityInfo.setLastLoginTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        userWriteService.updateLastLoginTime(userEntityInfo);
        //角色集合
        Set<GrantedAuthority> authorities = new HashSet<>();

        List<RoleEntity> roleEntities = userReadService.getRoleByUserId(userEntityInfo.getId());
        for (RoleEntity roleEntity : roleEntities) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + roleEntity.getRoleCode()));
        }

        userEntityInfo.setAuthorities(authorities);


        return new UsernamePasswordAuthenticationToken(username,password,authorities);

    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
